//
//  MobileLoginViewController.m
//  Fangmm
//
//  Created by 阮琦 on 16/3/10.
//  Copyright © 2016年 com.fangmm. All rights reserved.
//

#import "MobileLoginViewController.h"
#import "NewRequirementViewController.h"
#import "MainNavigationViewController.h"

#import "AppDrawer.h"

#import "ACMacros.h"
#import "Utility.h"
#import "Constants.h"
#import "HttpServer.h"
#import "User.h"
#import "Requirement.h"

#import <TSMessages/TSMessageView.h>
#import <MobClick.h>


@interface MobileLoginViewController () <UITextFieldDelegate>

@end

@implementation MobileLoginViewController {
    BOOL isMobileLegal;
    BOOL isVcodeLegal;
    BOOL isRequired;
    
    NSTimer *timer;
    NSInteger timeCount;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self insertBackground];
    [self configureTextViews];
    [self configureTapGestures];
    [self configureButton];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewWillAppear:(BOOL)animated {
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    if ([Utility getObjectForKey:kRequirement] == nil) {
        isRequired = false;
    } else {
        isRequired = true;
    }
    [MobClick beginLogPageView:@"手机登录页"];
}

- (void)viewWillDisappear:(BOOL)animated {
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    [MobClick endLogPageView:@"手机登录页"];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
#pragma mark - Configuring the view’s layout behavior
- (void)insertBackground {
    UIImageView *backgroundImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, Main_Screen_Width, Main_Screen_Height)];
    [backgroundImageView setImage:[UIImage imageNamed:@"login_bg.jpg"]];
    [self.view insertSubview:backgroundImageView atIndex:0];
}

- (void)configureTextViews {
    [self.mobileTextfield setDelegate:self];
    [self.vcodeTextfield setDelegate:self];
}

- (void)configureTapGestures {
    UITapGestureRecognizer *tapCancelInput = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(canelInput)];
    [self.view addGestureRecognizer:tapCancelInput];
}

- (void)configureButton {
    [self.vcodeButton setUserInteractionEnabled:false];
    [self.vcodeButton addTarget:self action:@selector(clickToGetVcode) forControlEvents:UIControlEventTouchUpInside];
}

#pragma mark - Text field delegate
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    [UIView animateWithDuration:0.2 animations:^{
        [UIView setAnimationBeginsFromCurrentState:YES];
        [self.view setFrame:CGRectMake(0, -120, Main_Screen_Width, Main_Screen_Height)];
    }];
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    [UIView animateWithDuration:0.2 animations:^{
        [UIView setAnimationBeginsFromCurrentState:YES];
        [self.view setFrame:CGRectMake(0, 0, Main_Screen_Width, Main_Screen_Height)];
    }];
    if ([textField isEqual:self.mobileTextfield]) {
        if ([self isValidateTelWithTel:textField.text]) {
            NSLog(@"legal");
        } else {
            [TSMessage showNotificationInViewController:self title:@"手机号码错误!" subtitle:@"请输入正确的手机号码" type:TSMessageNotificationTypeError duration:2.0 canBeDismissedByUser:true];
        }
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSString *value = textField.text;
    if ([string isEqual:@""]) {
        value = [value substringToIndex:textField.text.length - 1];
    } else {
        value = [NSString stringWithFormat:@"%@%@",value, string];
    }
    if (value.length == 11) {
        if ([self isValidateTelWithTel:value]) {
            [self.vcodeButton setTitleColor:RGBACOLOR(71, 16, 12, 1) forState:UIControlStateNormal];
            [self.vcodeButton.titleLabel setFont:[UIFont boldSystemFontOfSize:15]];
            [self.vcodeButton setUserInteractionEnabled:true];
        } else {
            [TSMessage showNotificationInViewController:self title:@"手机号码不合法!" subtitle:@"请输入正确的手机号码" type:TSMessageNotificationTypeError duration:2.0 canBeDismissedByUser:true];
        }
    } else {
        [self.vcodeButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [self.vcodeButton.titleLabel setFont:[UIFont systemFontOfSize:15]];
        [self.vcodeButton setUserInteractionEnabled:false];
    }
    return true;
}
#pragma mark - Configuring the view’s layout behavior
- (void)canelInput {
    [self.mobileTextfield resignFirstResponder];
    [self.vcodeTextfield resignFirstResponder];
}

#pragma mark - checkinputs methods
-(BOOL)isValidateTelWithTel:(NSString*)tel
{
    NSString *patternTel = @"^1[3,4,5,7,8][0-9]{9}$";
    NSError *err = nil;
    NSRegularExpression *TelExp = [NSRegularExpression regularExpressionWithPattern:patternTel options:NSRegularExpressionCaseInsensitive error:&err];
    NSTextCheckingResult *isMatchTel = [TelExp firstMatchInString:tel options:0 range:NSMakeRange(0, [tel length])];
    if (isMatchTel)
    {
        isMobileLegal = true;
        NSLog(@"手机号码合法");
    }
    else
    {
        isMobileLegal = false;
        NSLog(@"手机号码不合法");
    }
    return isMobileLegal;
}

#pragma mark - Triggering Methods
- (void)clickToGetVcode {
    timeCount = 59;
    [self.vcodeButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.vcodeButton.titleLabel setFont:[UIFont systemFontOfSize:15]];
    timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerCount) userInfo:nil repeats:YES];
    [self verifyCodeRequest];
}

- (IBAction)clickToLogin:(UIButton *)sender {
    [self.vcodeTextfield resignFirstResponder];
    [self.mobileTextfield resignFirstResponder];
    if (self.oauthId == nil) {
        self.oauthId = @"";
    }
    [HttpServer postToLoginWithMobile:self.mobileTextfield.text Vcode:self.vcodeTextfield.text AndOauthId:self.oauthId WithSuccessBlock:^(NSDictionary *successDic) {
        if ([[successDic allKeys]containsObject:@"user"]) {
            [[User sharedUser] setValuesForKeysWithDictionary:[successDic objectForKey:@"user"]];
            [Utility setObject:[User sharedUser] key:kUser];
            [Utility setObject:[User sharedUser].userId key:kUserId];
        }
        if ([[successDic allKeys]containsObject:@"requirement"]) {
            Requirement *requirement = [[Requirement alloc]initWithDic:[successDic objectForKey:@"requirement"]];
            [Utility setObject:requirement key:kRequirement];
            isRequired = true;
        } else {
            isRequired = false;
        }
        if ([[successDic allKeys]containsObject:@"token"]) {
            [Utility setObject:[successDic objectForKey:@"token"] key:kToken];
        }
//        if (isRequired) {
            [[AppDrawer sharedDrawer] removeFromParentViewController];
            [self presentViewController:[AppDrawer rebuildDrawer] animated:true completion:^{
            }];
//        } else {
//            NewRequirementViewController *newRequirementVC = [[NewRequirementViewController alloc]initWithNibName:@"NewRequirementViewController" bundle:nil];
//            [self presentViewController:newRequirementVC animated:true completion:^{
//            }];
//        }
    } withFailBlock:^(id failData) {
        NSLog(@"%@",failData);
        if ([[failData allKeys]containsObject:@"code"]) {
            if ([[NSString stringWithFormat:@"%@",[failData objectForKey:@"code"]]isEqualToString:@"200000"] ) {
                [TSMessage showNotificationInViewController:self title:@"验证码错误!" subtitle:@"请输入正确的验证码" type:TSMessageNotificationTypeError duration:2.0 canBeDismissedByUser:true];
            }
        }
         else {
            [TSMessage showNotificationInViewController:self title:@"网络错误!" subtitle:@"请稍后重试" type:TSMessageNotificationTypeError duration:2.0 canBeDismissedByUser:true];
        }
    }];
}


- (void)timerCount {
    self.vcodeButton.userInteractionEnabled = false;
    NSString *buttonTitle = [NSString stringWithFormat:@"%ld秒后重发",(long)timeCount];
    [self.vcodeButton setTitle:buttonTitle forState:UIControlStateNormal];
    timeCount--;
    if (timeCount <= 0) {
        [timer invalidate];
        self.vcodeButton.userInteractionEnabled = true;
        [self.vcodeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
        [self.vcodeButton setTitleColor:RGBACOLOR(71, 16, 12, 1) forState:UIControlStateNormal];
        [self.vcodeButton.titleLabel setFont:[UIFont boldSystemFontOfSize:15]];
    }
}

#pragma mark - Network methods
- (void)verifyCodeRequest {
    [HttpServer postToGetNewRegisterVcodeWithMobile:self.mobileTextfield .text WithSuccessBlock:^(NSDictionary *successDic) {
        
    } withFailBlock:^(id failData) {
        NSLog(@"%@",failData);
    }];
}

- (IBAction)clickToCancelPop:(UIButton *)sender {
    [self dismissViewControllerAnimated:true completion:^{
        
    }];
}

@end
